<template>
    <div id="CropperImage" class="PictureCropper-container">
        <el-button type="primary" plain size="small" icon="el-icon-picture" @click="dialogVisible = true">上传图片</el-button>
        <el-dialog
            :close-on-click-modal="false"
            title="图片裁剪"
            :visible.sync="dialogVisible"
            width="1200px">
            <div class="cropper_box">
                <div class="optionBtn">
                    <label class="btn" for="uploads">选择图片</label>
                    <input type="file" id="uploads" style="position:absolute; clip:rect(0 0 0 0);"
                           accept="image/png, image/jpeg, image/gif, image/jpg"
                           @change="uploadImg($event)">
                </div>
                <div class="cut_box">
                    <div class="cut">
                        <vue-cropper
                            ref="cropper"
                            :img="option.img"
                            :output-size="option.size"
                            :output-type="option.outputType"
                            :info="option.info"
                            :canScale="option.canScale"
                            :autoCrop="option.autoCrop"
                            :autoCropWidth="option.autoCropWidth"
                            :autoCropHeight="option.autoCropHeight"
                            :fixed="option.fixed"
                            :fixedNumber="option.fixedNumber"
                            :full="option.full"
                            :fixedBox="option.fixedBox"
                            :canMove="option.canMove"
                            :canMoveBox="option.canMoveBox"
                            :original="option.original"
                            :centerBox="option.centerBox"
                            :height="option.height"
                            :infoTrue="option.infoTrue"
                            :maxImgSize="option.maxImgSize"
                            :enlarge="option.enlarge"
                            :mode="option.mode"
                            @realTime="realTime"
                        ></vue-cropper>
                    </div>
                    <!--         预览效果     zoom固定裁剪框的大小      -->
                    <div class="show-preview"
                         :style="{'width': previews.w + 'px', 'height': previews.h + 'px', 'zoom': 400 / previews.h, 'zoom': 400 / previews.w,'overflow': 'hidden'}">
                        <div :style="previews.div" style="background-color: #000000">
                            <img :src="previews.url" :style="previews.img" style="max-width: none">
                        </div>
                    </div>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="getpicture('blob')">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
 
<script>
    import {VueCropper} from 'vue-cropper'
 
    export default {
        name: "CropperImage",
        components: {
            VueCropper
        },
        data() {
            return {
                dialogVisible: false,
                previews: {
                    w:400,
                    h:400
                },
                option: {
                    img: '',             //裁剪图片的地址
                    outputSize: 1,       //裁剪生成图片的质量(可选0.1 - 1)
                    outputType: 'jpeg',  //裁剪生成图片的格式（jpeg || png || webp）
                    info: true,          //图片大小信息
                    canScale: true,      //图片是否允许滚轮缩放
                    autoCrop: true,      //是否默认生成截图框
                    autoCropWidth: 657,  //默认生成截图框宽度
                    autoCropHeight: 440, //默认生成截图框高度
                    fixed: false,         //是否开启截图框宽高固定比例
                    fixedNumber: [1, 1], //截图框的宽高比例
                    full: false,         //false按原比例裁切图片，不失真
                    fixedBox: true,      //固定截图框大小，不允许改变
                    canMove: true,      //上传图片是否可以移动
                    canMoveBox: true,    //截图框能否拖动
                    original: true,     //上传图片按照原始比例渲染
                    centerBox: false,    //截图框是否被限制在图片里面
                    height: true,        //是否按照设备的dpr 输出等比例图片
                    infoTrue: false,     //true为展示真实输出图片宽高，false展示看到的截图框宽高
                    maxImgSize: 3000,    //限制图片最大宽度和高度
                    enlarge: 1,          //图片根据截图框输出比例倍数
                    mode: 'contain'  //图片默认渲染方式
                },
                uploadUrl: ``,// 图片上传地址
            };
        },
        methods: {
            // 实时预览函数
            realTime(data) {
                this.previews = data
            },
            //上传图片
            getpicture(type) {
                let _this = this;
                if (type === 'blob') {
                    //获取截图的blob数据
                    this.$refs.cropper.getCropBlob(async (data) => {
                        let formData = new FormData();
                        formData.append('file', data)
                        //调用axios上传
                        let {data: res} = await _this.$api.pictureUpload(formData) // 项目中封装的请求接口，需要修改
                        if (res.code === 0) {
                            _this.$message({
                                message: '上传成功！',
                                type: "success"
                            });
                            this.dialogVisible = false
                            _this.$emit('imgUpload', res.url);
                        } else {
                            _this.$message({
                                message: '文件服务异常，请联系管理员！',
                                type: "error"
                            });
                        }
                    })
                }
            },
            uploadImg(e) {
                //上传图片
                // this.option.img
                var file = e.target.files[0]
                if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
                    this.$message('图片类型必须是.gif,jpeg,jpg,png,bmp中的一种')
                    return false
                }
                var reader = new FileReader()
                reader.onload = (e) => {
                    let data
                    if (typeof e.target.result === 'object') {
                        // 把Array Buffer转化为blob 如果是base64不需要
                        data = window.URL.createObjectURL(new Blob([e.target.result]))
                    } else {
                        data = e.target.result
                    }
                    this.option.img = data
                }
                // 转化为base64
                // reader.readAsDataURL(file)
                // 转化为blob
                reader.readAsArrayBuffer(file)
            },
        }
    }
</script>
 
<style scoped lang="scss">
    .cropper_box {
        .optionBtn{
            margin-bottom: 15px;
        }
    }
 
  
 
    .show-preview {
        border: 1px solid #cccccc;
        margin-left: 5%;
    }
 
    .cut_box {
        display: flex;
    }
 
    .cut {
        width: 680px;
        height: 500px;
    }
 
    .c-item {
        max-width: 800px;
        margin: 10px auto;
        margin-top: 20px;
    }
 
    .content {
        margin: auto;
        max-width: 1200px;
        margin-bottom: 100px;
    }
 
    .test-button {
        display: flex;
        flex-wrap: wrap;
        align-content: center;
        justify-content: center;
    }
 
    .btn {
        display: inline-block;
        line-height: 1;
        white-space: nowrap;
        cursor: pointer;
        background: #fff;
        border: 1px solid #c0ccda;
        color: #1f2d3d;
        text-align: center;
        box-sizing: border-box;
        outline: none;
        margin: 20px 10px 0px 0px;
        padding: 9px 15px;
        font-size: 14px;
        border-radius: 4px;
        color: #fff;
        background-color: #50bfff;
        border-color: #50bfff;
        transition: all .2s ease;
        text-decoration: none;
        user-select: none;
    }
 
    .des {
        line-height: 30px;
    }
 
    code.language-html {
        padding: 10px 20px;
        margin: 10px 0px;
        display: block;
        background-color: #333;
        color: #fff;
        overflow-x: auto;
        font-family: Consolas, Monaco, Droid, Sans, Mono, Source, Code, Pro, Menlo, Lucida, Sans, Type, Writer, Ubuntu, Mono;
        border-radius: 5px;
        white-space: pre;
    }
 
    .show-info {
        margin-bottom: 50px;
    }
 
    .show-info h2 {
        line-height: 50px;
    }
 
    /*.title, .title:hover, .title-focus, .title:visited {
      color: black;
    }*/
 
    .title {
        display: block;
        text-decoration: none;
        text-align: center;
        line-height: 1.5;
        margin: 20px 0px;
        background-image: -webkit-linear-gradient(left, #3498db, #f47920 10%, #d71345 20%, #f7acbc 30%, #ffd400 40%, #3498db 50%, #f47920 60%, #d71345 70%, #f7acbc 80%, #ffd400 90%, #3498db);
        color: transparent;
        -webkit-background-clip: text;
        background-size: 200% 100%;
        animation: slide 5s infinite linear;
        font-size: 40px;
    }
 
    .test {
        height: 500px;
    }
 
 
    .c-item {
        display: block;
        user-select: none;
    }
 
    @keyframes slide {
        0% {
            background-position: 0 0;
        }
        100% {
            background-position: -100% 0;
        }
    }
 
</style>